package com.chen.base.module.mybatis.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.chen.base.module.mybatis.component.DataScopeSqlInjector;
import com.chen.base.module.mybatis.component.DynamicDataSourceDruidProperty;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Spring Boot 方式
 * @author ChenJinLong
 */
@Configuration
@MapperScan(value = {"com.chen.base.module.mybatis.mapper"})
public class MybatisPlusAutoConfig {

    /**
     * 插件配置
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        // 针对 update 和 delete 语句, 作用: 阻止恶意的全表更新删除
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        return interceptor;
    }

    /**
     * 扩展 mybatis-plus baseMapper
     */
    @Bean
    public DataScopeSqlInjector dataScopeSqlInjector() {
        return new DataScopeSqlInjector();
    }

    /**
     * SQL 日志格式化
     *
     * @return DruidSqlLogFilter
     */
    @Bean
    public DruidSqlLogFilter sqlLogFilter() {
        return new DruidSqlLogFilter();
    }

    @Bean
    public DefaultMetaObjectHandler defaultMetaObjectHandler(){
        return new DefaultMetaObjectHandler();
    }

    @Bean
    public DynamicDataSourceDruidProperty dynamicDataSourceDruidProperty(){
        return new DynamicDataSourceDruidProperty();
    }
}